package com.myspring.utils;

/**
 * ClassName: TransactionManager
 * Package: com.myspring.utils
 * Description:
 *
 * @Author 刘英杰
 * @Create 2025/2/1 19:45
 * @Version 1.0
 */


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * 事务管理器中封装开启事务,提交事务,回滚事务,释放资源
 */
@Component
public class TransactionManager {

    @Autowired
    ConnectionFactory connectionFactory;

    @Autowired
    ThreadLocal<Connection> threadLocal;
    /**
     * 开启事务
     */
    public void beginTransaction() {
        try {
            connectionFactory.currentThreadConn().setAutoCommit(false);
        } catch (SQLException throwables) {
            throw new RuntimeException(throwables.getMessage());
        }
    }

    /**
     * 提交事务
     */
    public void commit() {
        try {
            connectionFactory.currentThreadConn().commit();
        } catch (SQLException throwables) {
            throw new RuntimeException(throwables.getMessage());
        }
    }

    /**
     * 回滚事务
     */
    public void rollback() {
        try {
            connectionFactory.currentThreadConn().rollback();
        } catch (SQLException throwables) {
            throw new RuntimeException(throwables.getMessage());
        }
    }

    /**
     * 释放资源:释放数据库连接(将连接重新放回连接池)
     */
    public void release() {
        try {
            connectionFactory.currentThreadConn().close();
            threadLocal.remove();//将数据库连接与当前线程解绑,解绑后该连接可以与其它线程绑定
        } catch (SQLException throwables) {
            throw new RuntimeException(throwables.getMessage());
        }
    }

}
